import { defineStore } from 'pinia'
import { userService } from '../services/userService'

export const useUserStore = defineStore('user', {
    state: () => ({
        users: [],
        currentUser: null,
        loading: false,
        error: null
    }),

    getters: {
        getUserById: (state) => (id) => {
            return state.users.find(user => user._id === id)
        },

        userCount: (state) => state.users.length
    },

    actions: {
        async fetchUsers() {
            this.loading = true
            this.error = null
            try {
                const response = await userService.getAllUsers()
                this.users = response.data || response
            } catch (error) {
                this.error = error.message || '获取用户列表失败'
                console.error('获取用户失败:', error)
            } finally {
                this.loading = false
            }
        },

        async createUser(userData) {
            this.loading = true
            this.error = null
            try {
                const response = await userService.createUser(userData)
                this.users.push(response.data || response)
                return response.data || response
            } catch (error) {
                this.error = error.message || '创建用户失败'
                console.error('创建用户失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        async updateUser(id, userData) {
            this.loading = true
            this.error = null
            try {
                const response = await userService.updateUser(id, userData)
                const index = this.users.findIndex(user => user._id === id)
                if (index !== -1) {
                    this.users[index] = response.data || response
                }
                return response.data || response
            } catch (error) {
                this.error = error.message || '更新用户失败'
                console.error('更新用户失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        async deleteUser(id) {
            this.loading = true
            this.error = null
            try {
                await userService.deleteUser(id)
                this.users = this.users.filter(user => user._id !== id)
            } catch (error) {
                this.error = error.message || '删除用户失败'
                console.error('删除用户失败:', error)
                throw error
            } finally {
                this.loading = false
            }
        },

        clearError() {
            this.error = null
        }
    }
})
